/**
 * Created by huachuan on 2016/1/4.
 */
angular.module('meetingdetailcontrollers',[])
  //发现的首页（约局）的Controller
   .controller('MeetingDetailCtrl',function($scope,$state,$rootScope,$cordovaStatusbar,$cordovaFileTransfer,$timeout,$ionicPopup,$ionicActionSheet,$stateParams,Loading,Meeting,History,ShareServiceOther,ENV,Storage,Toast,ShareService){
      //参数获取
      var mmId = $stateParams['mmId'];
      var  memberId = Storage.get('member').member_id;
      $scope.picPath = ENV.picPath;
      $scope.isShareShow = ShareService.getIsShowShareWindow();//判断是否显示分享框

    //酒窝显示大图
    $scope.showBigImage= function(){
      var items = [{
        src:$scope.picPath+"big_"+$scope.meetingDetail.acitivityDetail.mm_img_url,
        w:$scope.meetingDetail.w,
        h:$scope.meetingDetail.h
      }];
      var pswpElement = document.querySelectorAll('.pswp')[0];
      var options = {
        index: 1,
        history: false,
        focus: false,
        loop: false,
   /*     pinchToClose:false,
        closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true,
        loadingIndicatorDelay:100
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
    //  $cordovaStatusbar.hide();
    }
    //长按下载
    $rootScope.downloadHomeImg = function(){
      var url = $rootScope.gallery.currItem.src;
      var timestamp=new Date().getTime();
      var targetPath = targetPath = cordova.file.externalRootDirectory+"winelife/winelife_discover_"+timestamp+".jpg";
      var trustHosts = true;
      var options = {};
      $ionicActionSheet.show({
        buttons: [
          {text: '保存到手机相册'}
        ],
        cancelText: '取消',
        buttonClicked: function (index) {
          if(index==0){
            $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
              .then(function(result) {
                Toast.showMessage("保存成功");
              }, function(err) {
                Toast.showMessage("保存成功");
              }, function (progress) {
              });
          }
          return true;
        }
      });
    }
    //单击缩小图片
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
     // $cordovaStatusbar.show();
    }

    //点击头像跳转到用户的个人信息
    $scope.go2MemberInfo = function(memberId){
      $state.go('member-data',{'memberId':memberId});
    }

      //跳转到店铺详情
      $scope.go2shop = function(){
        shopId = $scope.meetingDetail.acitivityDetail.shop_id;
        if(shopId!=null && shopId!=''&& shopId!=undefined&&shopId!=0){
              $state.go('shop-details',{shopId:shopId});
        }else{
          Toast.showMessage("该约局无店铺详情");
        }
      }
      //是否是第一次进入
      var firstIn = true;
    $scope.$on('$ionicView.beforeEnter', function () {
      memberId = Storage.get('member').member_id;
      if(!firstIn){
        Meeting.getSignInPersionList(mmId);//加载报名人数和列表
        Meeting.getMeetingCurMsg(memberId,mmId);
      }else{
        Loading.showLoading();
      }
      firstIn = false;
    });
    //页面加载完成后再进行页面请求
    Meeting.getMeetingDetail(mmId,memberId);
    //网络访问请求成功的之后
    $scope.$on('Meeting.signInPersionListUpdated',function(){
      var result = Meeting.getSignInPersionListJson();
      $scope.meetingDetail.personList = result.personList;
    })
    //更新界面上的信息
    $scope.$on('Meeting.meetingCurMsgUpdated',function(){
      var result = Meeting.getMeetingCurMsgJson();
      $scope.meetingDetail.hasSignIn = result.hasSignIn;
      $scope.meetingDetail.mcmeetStatus = result.mcmeetStatus;
      $scope.meetingDetail.outofDate = result.outofDate;
      $scope.meetingDetail.outofDealDate = result.outofDealDate;
      $scope.meetingDetail.fullPersonNum = result.fullPersonNum;
      $scope.meetingDetail.iReleaseStatus = result.iReleaseStatus;
      $scope.meetingDetail.inviteMeStatus = result.inviteMeStatus;
      $scope.meetingDetail.acitivityDetail.mm_comment_num = result.mm_comment_num;
      if(result.inviteMeStatus){
        $scope.meetingDetail.mmi_state = result.mmi_state
      }
      if($scope.meetingDetail.hasSignIn){
        $scope.signInBtn = '取消报名';
      }else{
        $scope.signInBtn = '我要报名';
      }
      Loading.hideLoading();
    });

      $scope.isShowWine = true;
      $scope.showWine = function(){$scope.isShowWine = true;}
      $scope.showDesc = function(){$scope.isShowWine = false;}
      //底部按钮显示的内容
      $scope.signInBtn = '我要报名';

    //收藏
    $scope.collectMeeting = function(){
      Loading.showLoading();
      Meeting.collectMeeting(memberId,mmId);
    };
    //网络访问成功后
    $scope.$on('Meeting.collectMeetingUpdated', function(){
      Loading.hideLoading();
      var result = Meeting.getCollectJson();
      $scope.meetingDetail.mcmeetStatus = result.mcmeetStatus;
      Toast.showMessage(result.mcmeetMsg);
    })

    /*********************点赞***********************/
    $scope.likeMeeting = function(){
      Loading.showLoading();
      Meeting.likeMeeting(memberId,mmId);
    }
    //网络访问成功后
    $scope.$on('Meeting.likeMeetingUpdated', function(){
      Loading.hideLoading();
      var result = Meeting.getLikeJson();
      $scope.meetingDetail.lmeetStatus = result.lmeetStatus;
      Toast.showMessage(result.lmeetMsg);
    })
    $scope.$on('Meeting.meetingDetailUpdated', function(){
      $scope.meetingDetail = Meeting.getMeetingDetailJson();
      var mmAddr =$scope.meetingDetail.acitivityDetail.mm_address_show = $scope.meetingDetail.acitivityDetail.mm_address;
      if(mmAddr.length>20){
        $scope.meetingDetail.acitivityDetail.mm_address_show = mmAddr.substring(0,17)+"<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+mmAddr.substring(17);
      }
      if($scope.meetingDetail.hasSignIn){
        $scope.signInBtn = '取消报名';
      }else{
        $scope.signInBtn = '我要报名';
      }
      Loading.hideLoading();
    });
    /*************************底部按钮的处理*********************/
    //取消报名和报名该约局
    $scope.showCancelSignIn = false;//显示取消报名
    $scope.go2SignIn = function(){
        if($scope.signInBtn == '我要报名'){
          if($scope.meetingDetail.outofDate){//约局已经过期
            Toast.showMessage('约局已过期');
          }else if($scope.meetingDetail.outofDealDate){
            Toast.showMessage("报名已过期，无法进行操作");
          }else if($scope.meetingDetail.fullPersonNum){
            Toast.showMessage("报名人数已满，无法报名");
          } else if($scope.meetingDetail.hasSignIn){//已经报名该约局
            Toast.showMessage('您已报名,无需重复报名');
          }else{
            $state.go('enroll-from',{mmId:mmId});
            //保存约局的群组二维码
            Meeting.setMeetingCodeImg($scope.meetingDetail.acitivityDetail.mm_groupcode_img_url);
          }
        }else if($scope.signInBtn == '取消报名'){
            $ionicPopup.confirm({
              template: '<p style="text-align: center;font-size:16px;">确定要取消报名吗？</p>',
              cancelText: '取消',
              okText: '确定',
              okType: 'hd-red-btn',
              cancelType: 'cancel-esc-btn'
            }).then(function (res) {
              if (res) {
                Loading.showLoading();
                Meeting.signOutMeeting(memberId,mmId);
              }
            });
          //$scope.showCancelSignIn = true;
        }
    }
    //取消报名
    $scope.signOutInvitedMeeting = function(){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要取消报名吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          Loading.showLoading();
          Meeting.signOutMeeting(memberId,mmId);
        }
      });
    }
    /*//确定取消报名
    $scope.confirmCancelSignIn = function(){
      Loading.showLoading();
      $scope.showCancelSignIn = false;

    }*/
    //网络请求成功之后
    $scope.$on('Meeting.signOutMeetingUpdated',function(){
      Loading.hideLoading();
        var result = Meeting.getSignOutMeetingJson();
        if(result.signOutState){
          $scope.meetingDetail.hasSignIn = false;
          if($scope.meetingDetail.hasSignIn){
            $scope.signInBtn = '取消报名';
          }else{
            $scope.signInBtn = '我要报名';
          }
          Meeting.getSignInPersionList(mmId);
          Meeting.getMeetingCurMsg(memberId,mmId);
        }
      Toast.showMessage(result.signOutMsg);
    });
    $scope.phoneCall = function(phoneNum){
      if(phoneNum!=undefined&&phoneNum!=''){
        if(ionic.Platform.isAndroid()){
          document.location.href = "tel:"+phoneNum;
        }else if(ionic.Platform.isIOS()){
          phonedialer.dial(phoneNum,function(err) {
            if (err == "feature")
              console.log("您的设备不支持");
            if (err == "empty")
              Toast.showMessage("未知的电话号码");
          });
        }
      }else{
        Toast.showMessage("号码不存在");
      }
    }
   /* //取消
    $scope.cancel = function(){
      $scope.showCancelSignIn = false;
      $scope.showInviteMe = false;
      $scope.showCancelMeeting = false;
    }*/
    //拒绝邀请该约局，同意该约局
    $scope.popupContent = '';//弹出层显示的信息
    $scope.showInviteMe = false;
    $scope.cancelInvite = function(){//拒绝邀请
      if($scope.meetingDetail.outofDate){
        Toast.showMessage("约局已过期，无法操作");
      }else{
        $ionicPopup.confirm({
          template: '<p style="text-align: center;font-size:16px;">确定要拒绝该约局吗？</p>',
          cancelText: '取消',
          okText: '确定',
          okType: 'hd-red-btn',
          cancelType: 'cancel-esc-btn'
        }).then(function (res) {
          if (res) {
            Loading.showLoading();
            Meeting.updateInviteMe(memberId,mmId,'拒绝');//更新对邀请我的处理
          }
        });
       /* $scope.popupContent = '拒绝';
        $scope.showInviteMe = true;*/
      }
    }
    $scope.aggreeInvite = function(){//同意邀请
      if($scope.meetingDetail.outofDate){
        Toast.showMessage("约局已过期，无法操作");
      }else if($scope.meetingDetail.outofDealDate){
        Toast.showMessage("约局报名已结束，无法操作");
      }else{
        $ionicPopup.confirm({
          template: '<p style="text-align: center;font-size:16px">确定要同意该约局吗？</p>',
          cancelText: '取消',
          okText: '确定',
          okType: 'hd-red-btn',
          cancelType: 'cancel-esc-btn'
        }).then(function (res) {
          if (res) {
            Loading.showLoading();
            Meeting.updateInviteMe(memberId,mmId,'同意');//更新对邀请我的处理
          }
        });
       /* $scope.popupContent = '同意';
        $scope.showInviteMe = true;*/
      }
    }
    /*$scope.confirmInviteMe = function(){
      Loading.showLoading();
      $scope.showInviteMe = false;
      Meeting.updateInviteMe(memberId,mmId,$scope.popupContent);//更新对邀请我的处理
    }*/
    $scope.$on('Meeting.dealInviteMeMeetingUpdated',function(){
      Loading.hideLoading();
      var result = Meeting.getDealInviteMeJson();
      if(result.inviteMeState){
        $scope.meetingDetail.mmi_state = result.mmi_state;
        if($scope.meetingDetail.mmi_state=='同意'){
          Meeting.getSignInPersionList(mmId);//重新获取报名列表
        }
      }
      Toast.showMessage(result.inviteMeMsg);
    });
    //编辑约局
    $scope.editMeeting = function(){
      Storage.set("updateMeeting",$scope.meetingDetail.acitivityDetail);
      $state.transitionTo('release-date');
    }
    //取消该约局
    //$scope.showCancelMeeting = false;//是否显示取消约局的弹出层
    $scope.cancelMeeting = function(){
      if($scope.meetingDetail.outofDate){
        Toast.showMessage("约局已过期，无需取消");
      }else if($scope.meetingDetail.personList.length>0){
        Toast.showMessage("已有好友报名，无法取消");
      }else{
        $ionicPopup.confirm({
          template: '<p style="text-align: center;font-size:16px">确定要取消该约局吗？</p>',
          cancelText: '取消',
          okText: '确定',
          okType: 'hd-red-btn',
          cancelType: 'cancel-esc-btn'
        }).then(function (res) {
          if (res) {
            Loading.showLoading();
            //取消该约局
            Meeting.cancelMeeting(memberId,mmId);
          }
        });
       // $scope.showCancelMeeting = true;
      }
    }
   /* $scope.confirmCancelMeeting = function(){
      Loading.showLoading();
      $scope.showCancelMeeting = false;
      //取消该约局
      Meeting.cancelMeeting(memberId,mmId);
    }*/
    $scope.$on('Meeting.cancelMeetingUpdated',function(){
      Loading.hideLoading();
      var result = Meeting.getCancelMeetingJson();
      if(result.cancelState){
        $timeout(function(){
          $state.go("calendar");
        },1000);
      }
      Toast.showMessage(result.cancelMsg);
    });

    /* ========================分享约局按钮  begin======================= */
    //显示约局分享框
    $scope.showMeetingShare = function(mm_id){
      ShareServiceOther.showShareWindow(mm_id,"meeting");
    };
    /* =========================分享约局按钮  end =============================== */


  /***************************底部按钮处理结束*************************/
    //前往报名列表的时候进行缓存
      $scope.showApplyList = function(){
        $state.transitionTo('enroll-list',{mmId:mmId});
      };
    //返回
    $scope.goback = function(){
      History.goback();
    };
    //改变数字的显示，添加逗号分割
    $scope.getFormatNum = function (num) {
      return formatNum(num);
    };
  })

//约局的评论Controller
  .controller('MeetingCommentCtrl',function($scope,$stateParams,$ionicPopup,Meeting,Loading,MeetingComment,ENV,Storage,Toast,History){
    $scope.picPath = ENV.picPath;
    var mmId = $stateParams['mmId'];
    var memberId = Storage.get('member').member_id;

    var isFirstIn = true;
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get('member').member_id;
      if(isFirstIn){
        Loading.showLoading();
        isFirstIn = false;
      }
      //获取评论列表
      MeetingComment.getCommentList(mmId,memberId);
    });

    $scope.commentList = [];
    $scope.memberInfo={
      member_img_url:'',
      mr_img_url:''
    };
    //新增评论
    $scope.comment={
      newComment:''
    };
    $scope.$on('Meeting.CommentListUpdated',function(){
      $scope.commentList=MeetingComment.getCommentJson().commentList;
      $scope.memberInfo.member_img_url =MeetingComment.getCommentJson().memberInfo.member_img_url;
      Loading.hideLoading();
    });

    //发表评论
    $scope.publishComment = function(){
      if($scope.comment.newComment==''){
        Toast.showMessage("评论的内容不能为空");
      }else{
        Loading.showLoading();
        MeetingComment.publishComment(mmId,memberId,$scope.comment.newComment);
        $scope.comment.newComment = '';//使得输入框中的值为空
      }
    };
    //请求网络数据完成之后
    $scope.$on('Meeting.publishCommentUpdated', function() {
      Loading.hideLoading();
      var newComment = MeetingComment.getNewComment();
      if(newComment.amCommentStatus){
        $scope.commentList.unshift(newComment);
      }
      Loading.hideLoading();
      Toast.showMessage(newComment.amCommentMsg);
    });
    //删除评论
    var deleteIndex = '';
    $scope.deleteComment = function(mmcId,index){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要删除该评论吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          Loading.showLoading();
          MeetingComment.deleteComment(mmcId,memberId,mmId);
          deleteIndex = index;
        }
      });

    }
    $scope.$on('Meeting.deleteCommentUpdated',function(){
        Loading.hideLoading();
        var result = MeetingComment.getDelCommentJson();
        if(result.dmCommentStatus){
          $scope.commentList.splice(deleteIndex,1);
        }
      Toast.showMessage(result.dmCommentMsg);
    });
    //返回
    $scope.goback = function(){
      History.goback();
    }
  })
;
